package com.pipe.servicepipe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pipe.servicepipe.entity.PipeDebt;
import com.pipe.servicepipe.entity.PipeSell;
import com.pipe.servicepipe.entity.vo.PipeSellQuery;
import com.pipe.servicepipe.mapper.PipeSellMapper;
import com.pipe.servicepipe.service.PipeDebtService;
import com.pipe.servicepipe.service.PipeSellService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 销售表 服务实现类
 * </p>
 *
 * @author hetao
 * @since 2020-07-12
 */
@Service
public class PipeSellServiceImpl extends ServiceImpl<PipeSellMapper, PipeSell> implements PipeSellService {
    @Resource
    private PipeDebtService pipeDebtService;

    @Override
    public void findByPage(Page page, PipeSellQuery query) throws Exception{
        QueryWrapper wrapper = new QueryWrapper();
        if (query != null) {
            String operator = query.getOperator();
            String startTime = query.getStartTime();
            String endTime = query.getEndTime();
            if (StringUtils.isNotEmpty(operator)) {
                wrapper.like("operator",operator);
            }
            if (StringUtils.isNotEmpty(startTime)) {
                wrapper.ge("create_time",startTime);
            }
            if (StringUtils.isNotEmpty(endTime)) {
                wrapper.le("create_time",endTime);
            }
        }
        this.baseMapper.selectPage(page,wrapper);
    }

    @Override
    @Transactional
    public void savePell(PipeSell pipeSell) throws Exception{
        pipeSell.setOperator(SecurityContextHolder.getContext().getAuthentication().getName());
        this.baseMapper.insert(pipeSell);
        if (pipeSell.getIsDebt() == 1) {
            PipeDebt debt = new PipeDebt();
            BeanUtils.copyProperties(pipeSell,debt);
            //赊账 移入欠款表
            debt.setTotalMoney(pipeSell.getPrice());
            debt.setRepayMoney(BigDecimal.ZERO);
            debt.setResidueMoney(BigDecimal.ZERO);
            pipeDebtService.save(debt);
        }
    }

    @Override
    @Transactional
    public void deleteById(String sid) throws Exception{
        this.baseMapper.deleteById(sid);
        this.pipeDebtService.deleteBySid(sid);
    }

    @Override
    @Transactional
    public void batchDel(String ids) throws Exception {
        List id = Arrays.asList(ids.split(","));
        this.baseMapper.deleteBatchIds(id);
        this.pipeDebtService.deleteBatchBySid(id);
    }
}
